require('buffer');
var express = require('express');
var router = express.Router();
var crypto = require('crypto');
var moment = require("moment");

const config = {
  "AccessKeyId" : "LTAIaO6zxMnMEY05",
  "AccessKeySecret" : "rKZ3xiiHCfA8aVlWWMArZX1v4Pvb2T"
};

var uploadCounter = 0;

router.get('/get_ststoken', function (req, res) {

  var fileNameSPlited = req.query.fileName.split(".");
  var extName = fileNameSPlited[fileNameSPlited.length - 1];

  var fileKey = "f" + ( ++ uploadCounter ) + "@" + new Date().getTime() + "." + extName;
  var eDate = new Date((new Date().getTime() + 1000 * 60 * 5));
  var policyText = {
    "expiration": moment().add(5, "minutes").utc().format(), //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
      [
        "content-length-range",
        0,
        1048576000
      ] // 设置上传文件的大小限制
    ]
  };

  const hmac = crypto.createHmac('SHA1', config.AccessKeySecret);

  var policyBase64 = new Buffer(JSON.stringify(policyText)).toString("base64");
  hmac.update(policyBase64);

  res.json({
    accessKeyId: config.AccessKeyId,
    signature: hmac.digest("base64"),
    policy: policyBase64,
    fileKey: fileKey
  });

});

module.exports = router;
